package service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import model.Accident;
import model.Accisqe;
import model.AciActivity;
import model.AciCause;
import model.Department;
import model.Injured;
import model.ProduceType;
import model.Producer;
import model.Product;
import model.User;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

import dao.AccidentDao;
import dao.AccisqeDao;
import dao.AciActiDao;
import dao.AciCauseDao;
import dao.DeptDao;
import dao.InjuredDao;
import dao.ProduceTypeDao;
import dao.ProducerDao;
import dao.ProductDao;
import dao.RoleDao;
import dao.UserDao;

@Service
public class AccidentService {
	@Autowired
	private AccidentDao accidentDao;
	private Accident accident;
	@Autowired
	private AciActiDao aciActiDao;
	private AciActivity aciActivity;
	@Autowired
	private AciCauseDao aciCauseDao;
	private AciCause aciCause;
	@Autowired
	private AccisqeDao accisqeDao;
	private Accisqe accisqe;
	@Autowired
	private ProducerDao producerDao;
	private Producer producer;
	@Autowired
	private ProductDao productDao;
	private Product product;
	@Autowired
	private ProduceTypeDao produceTypeDao;
	private ProduceType produceType;
	@Autowired
	private InjuredDao injuredDao;
	private Injured injured;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private DeptDao deptDao;

	public void saveOrUpdate(User user, Accident accident, Accisqe accisqe,
			Product product, Producer producer, Injured injured,
			String prodtypes, String causes, String activities) {
		accident.setLasttime(new Date());
		accident.setCreator(user.getId());
		if (accident.getId() == null) {
			/* 本区CODE */
			String code1 = queryDept(user.getDept()).getCode();
			/* 本社区CODE */
			String code2 = deptDao.getById(user.getDept()).getCode();
			/* 当前日期时间 */
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String dateStr = sdf.format(new Date());
			String code = code1 + code2 + dateStr;
			accident.setCode(code);
			accidentDao.save(accident);
		} else {
			accidentDao.update(accident);
		}

		Integer acid = accident.getId();
		/* 产品表 */
		product.setAcid(acid);
		if (product.getId() == null) {
			productDao.save(product);
		} else {
			productDao.update(product);
		}

		/* 生产者 */
		producer.setAcid(acid);
		if (producer.getId() == null) {
			producerDao.save(producer);
		} else {
			producerDao.update(producer);
		}

		/* 受伤害者 */
		injured.setAcid(acid);
		if (injured.getId() == null) {
			injuredDao.save(injured);
		} else {
			injuredDao.update(injured);
		}

		/* 关联表 */
		if (StringUtils.isNotBlank(prodtypes)) {
			String[] typeStrs = prodtypes.split(",");
			Integer prodid = product.getId();
			// 删除
			produceTypeDao.deleteByProdid(prodid);
			for (String type : typeStrs) {
				Integer typeid = Integer.parseInt(type);
				ProduceType _produceType = new ProduceType();
				_produceType.setProdid(prodid);
				_produceType.setType(typeid);
				// 新增
				produceTypeDao.save(_produceType);
			}
		}
		if (StringUtils.isNotBlank(causes)) {
			String[] causeStrs = causes.split(",");
			// 删除
			aciCauseDao.deleteByAccid(acid);
			for (String cause : causeStrs) {
				Integer causeid = Integer.parseInt(cause);
				AciCause _aciCause = new AciCause();
				_aciCause.setAcid(acid);
				_aciCause.setCauseid(causeid);
				// 新增
				aciCauseDao.save(_aciCause);
			}
		}
		if (StringUtils.isNotBlank(activities)) {
			String[] activityStrs = activities.split(",");
			// 删除
			aciActiDao.deleteByAccid(acid);
			for (String activity : activityStrs) {
				Integer activityid = Integer.parseInt(activity);
				AciActivity _aciActivity = new AciActivity();
				_aciActivity.setAcid(acid);
				_aciActivity.setActid(activityid);
				// 新增
				aciActiDao.save(_aciActivity);
			}
		}

	}

	public PageList<HashMap<String, Object>> queryPage(int page, int limit,
			User user, HashMap<String, Object> map) {
		List<HashMap<String, Object>> roles = roleDao.getRoles(user.getId());
		int roleFlag = 4; // 初始最低权限
		int deptid = 0; // 区ID
		for (int i = 0; i < roles.size(); i++) {
			Integer roleid = (Integer) roles.get(i).get("roleid");
			/* 最高权限:开发、系统 业务管理 */
			if (roleid.equals(1) || roleid.equals(7) || roleid.equals(8)) {
				roleFlag = 1;
				break; // 最高权限，跳出循环
			}
			/* 市质监局 */
			else if (roleid.equals(9)) {
				roleFlag = 2;
			}
			/* 区质监局 */
			else if (roleid.equals(10)) {
				roleFlag = 3;
			}
			/* 社区管理员以及平民 */
			else {
				roleFlag = 4;
			}
		}
		PageList<HashMap<String, Object>> pagelist = new PageList<HashMap<String, Object>>();
		PageBounds pageBounds = new PageBounds(page, limit);
		/* 列表无限制 */
		if (roleFlag == 1) {
			pagelist = (PageList<HashMap<String, Object>>) accidentDao
					.queryAllPage(pageBounds, map);
		}
		/* 市管理员限制：只显示本市信息 */
		else if (roleFlag == 2) {
			pagelist = (PageList<HashMap<String, Object>>) accidentDao
					.queryPage(pageBounds, map);
		}
		/* 区管理员限制：只显示本区信息 */
		else if (roleFlag == 3) {
			deptid = queryDept(user.getDept()).getId();
			@SuppressWarnings("rawtypes")
			ArrayList al = getDepts(deptid);
			map.put("deptids", al);
			pagelist = (PageList<HashMap<String, Object>>) accidentDao
					.queryDistrictPage(pageBounds, map);
		}
		/* 社区管理员以及平民 */
		else {
			String flag = (String) map.get("flag");
			if (StringUtils.isNotBlank(flag) && flag.equals("demo")) {
				map.remove("status");
				map.put("status", 1);
			}
			Integer userid = user.getId();
			map.put("userid", userid);
			pagelist = (PageList<HashMap<String, Object>>) accidentDao
					.queryUserPage(pageBounds, map);
		}

		return pagelist;
	}

	/* 查找区ID */
	public Department queryDept(Integer deptid) {
		Department department = deptDao.getById(deptid);
		if (department.getPid() == 0 || department.getPid() == 1) {
			return department;
		} else {
			return queryDept(department.getPid());
		}
	}

	/* 获取某区下所有机构ID */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ArrayList getDepts(Integer pid) {
		ArrayList al = new ArrayList();
		al.add(pid);
		List<Department> list = deptDao.queryTreeList(pid);
		for (int i = 0; i < list.size(); i++) {
			Integer tempid = list.get(i).getId();
			al.add(tempid);
			if (list.get(i).getLeaf().equals("false")) {
				getDepts(tempid);
			}
		}
		return al;
	}

	public void delete(String ids) {
		String[] idStrs = ids.split(",");
		for (String id : idStrs) {
			Integer _id = Integer.parseInt(id);
			// 删除
			accidentDao.delete(_id);
		}
	}

	public void submit(String ids) {
		String[] idStrs = ids.split(",");
		for (String id : idStrs) {
			Integer _id = Integer.parseInt(id);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("id", _id);
			map.put("status", 2);
			// 修改状态
			accidentDao.submit(map);
		}
	}

	public Integer countMy(HashMap<String, Object> map) {
		return accidentDao.countMy(map);
	}

	public List<HashMap<String, Object>> getById(Integer id) {
		return accidentDao.getById(id);
	}

	public List<HashMap<String, Object>> getActi(Integer accid) {
		return aciActiDao.getActi(accid);
	}

	public List<HashMap<String, Object>> getCause(Integer accid) {
		return aciCauseDao.getCause(accid);
	}

	public List<HashMap<String, Object>> getType(Integer accid) {
		return produceTypeDao.getType(accid);
	}

	public Accident getAccident() {
		return accident;
	}

	public void setAccident(Accident accident) {
		this.accident = accident;
	}

	public AciActivity getAciActivity() {
		return aciActivity;
	}

	public void setAciActivity(AciActivity aciActivity) {
		this.aciActivity = aciActivity;
	}

	public AciCause getAciCause() {
		return aciCause;
	}

	public void setAciCause(AciCause aciCause) {
		this.aciCause = aciCause;
	}

	public Accisqe getAccisqe() {
		return accisqe;
	}

	public void setAccisqe(Accisqe accisqe) {
		this.accisqe = accisqe;
	}

	public Producer getProducer() {
		return producer;
	}

	public void setProducer(Producer producer) {
		this.producer = producer;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public Injured getInjured() {
		return injured;
	}

	public void setInjured(Injured injured) {
		this.injured = injured;
	}

	public ProduceType getProduceType() {
		return produceType;
	}

	public void setProduceType(ProduceType produceType) {
		this.produceType = produceType;
	}

}
